package com.hp.bon.sgw.wh.channel.invoices.bizSlot;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hp.bon.sgw.wh.bean.CommonErrorDTO;
import com.hp.bon.sgw.wh.channel.common.BizConsts;
import com.hp.bon.sgw.wh.channel.common.BizParam;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.simpleframework.http.Request;

import java.io.*;
import java.util.*;

/**
 * @PROJECT_NAME: SGW_WH2.1_TMALL
 * @DESCRIPTION:
 * @USER: YouQi
 * @DATE: 2021/5/8 14:35
 */
public class HttpClientUtils {

    private static final Logger _log = LoggerFactory
            .getLogger(HttpClientUtils.class);

    public static String getHttpStr(String httpUrl, BizParam bizParam) {
        _log.info("===========http url===============" + httpUrl);
        String resp = "";
        GetMethod getMethod = new GetMethod(httpUrl);
        //请求头
        getMethod.setRequestHeader("Content-Type", bizParam.getParamString(BizConsts.RQUEST_HEADER_CONTENT_TYPE));
        getMethod.setRequestHeader("X-APP-ID", bizParam.getParamString(BizConsts.RQUEST_HEADER_X_APP_ID));
        getMethod.setRequestHeader("X-APP-KEY", bizParam.getParamString(BizConsts.RQUEST_HEADER_X_APP_KEY));
        getMethod.setRequestHeader("X-CTG-Request-ID", bizParam.getParamString(BizConsts.RQUEST_HEADER_X_CTG_REQUEST_ID));
        getMethod.setRequestHeader("X-CTG-Region-ID", bizParam.getParamString(BizConsts.RQUEST_HEADER_X_CTG_REGION_ID));
        try {
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5 * 1000);
            try {
                client.executeMethod(getMethod);
            } catch (HttpException e) {
                _log.info("===========http call timeout===============" + httpUrl);
                return "";
            } catch (IOException e) {
                _log.info("===========http call timeout session_id:");
                return "";
            }
            try {

                InputStream str = getMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(str));
                StringBuffer stringBuffer = new StringBuffer();
                String result = "";
                while ((result = br.readLine()) != null) {
                    stringBuffer.append(result);
                }
                resp = stringBuffer.toString();
                _log.info("===========http Resp Msg===============" + resp);
            } catch (IOException e) {
                _log.info("===========http call timeout===============" + httpUrl);
                return "";
            }
        } catch (Exception e) {
            _log.info("===========http call timeout===============" + httpUrl);
            e.printStackTrace();
            return "";
        }
        return resp;
    }


    public static String postHttpStr(String buildStringMes, String httpUrl, BizParam bizParam) {
        _log.info("===========http url===============" + httpUrl);
        _log.info("===========http Req  Msg===============" + buildStringMes);
        String resp = "";
        PostMethod post = new PostMethod(httpUrl);
        //请求头
        String content_type = bizParam.getParamString(BizConsts.RQUEST_HEADER_CONTENT_TYPE);
        post.setRequestHeader("Content-Type", content_type == null ? "" : content_type);
        String x_app_id = bizParam.getParamString(BizConsts.RQUEST_HEADER_X_APP_ID);
        post.setRequestHeader("X-APP-ID", x_app_id == null ? "" : x_app_id);
        String x_app_key = bizParam.getParamString(BizConsts.RQUEST_HEADER_X_APP_KEY);
        post.setRequestHeader("X-APP-KEY", x_app_key == null ? "" : x_app_key);
        String x_ctg_request_id = bizParam.getParamString(BizConsts.RQUEST_HEADER_X_CTG_REQUEST_ID);
        post.setRequestHeader("X-CTG-Request-ID", x_ctg_request_id == null ? "" : x_ctg_request_id);
        String x_ctg_region_id = bizParam.getParamString(BizConsts.RQUEST_HEADER_X_CTG_REGION_ID);
        post.setRequestHeader("X-CTG-Region-ID", x_ctg_region_id == null ? "" : x_ctg_region_id);
        try {
            RequestEntity requestEntity = new StringRequestEntity(buildStringMes, "application/json", "UTF-8");
            post.setRequestEntity(requestEntity);
            HttpClient client = new HttpClient();

            client.getHttpConnectionManager().getParams().setConnectionTimeout(5 * 1000);
            try {
                if (post == null) {
                    _log.info("===========post===============null");
                }
                _log.info("===========bizParam===============" + JSONObject.toJSONString(bizParam,true));
                _log.info("===========httpUrl===============" +httpUrl);
                _log.info("===========buildStringMes===============" +buildStringMes);
                client.executeMethod(post);
            } catch (HttpException e) {
                _log.info("===========http call timeout===============" + httpUrl);
                return "";
            } catch (IOException e) {
                _log.info("===========http call timeout session_id:");
                return "";
            }
            try {
                InputStream str = post.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(str));
                StringBuffer stringBuffer = new StringBuffer();
                String result = "";
                while ((result = br.readLine()) != null) {
                    stringBuffer.append(result);
                }
                resp = stringBuffer.toString();
                _log.info("===========http Resp Msg===============" + resp);
                //resp = post.getResponseBodyAsString();
            } catch (IOException e) {
                _log.info("===========webservice call timeout===============" + httpUrl);
                return "";
            }
        } catch (UnsupportedEncodingException e) {
            _log.info("===========webservice call timeout===============" + httpUrl);
            e.printStackTrace();
        }
        return resp;
    }


    public static String getErrorJsonStr(String code, String message, String reason, String referenceError) {
        List<CommonErrorDTO> CommonErrorDTOList = new ArrayList<>();
        CommonErrorDTO errorDTO = new CommonErrorDTO();
        errorDTO.setCode(code);
        errorDTO.setMessage(message);
        errorDTO.setReason(reason);
        errorDTO.setReferenceError(referenceError);
        CommonErrorDTOList.add(errorDTO);

        return JSON.toJSONString(CommonErrorDTOList);
    }


    public static String getRequestBody(Request request) {
        try {
            InputStream v_inputstream = request.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int x = 0;
            while ((x = v_inputstream.read()) != -1) {
                baos.write(x);
            }
            baos.flush();
            return new String(baos.toByteArray(), "UTF-8");
        } catch (Exception e) {
            _log.error(e.getMessage(), e);
        }
        return "";
    }

    public static Map<String, Object> parseJSON2Map(String jsonStr) {
        Map<String, Object> map = null;
        try {
            map = new HashMap<String, Object>();
            JSONObject json = JSONObject.parseObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        Object json2 = it.next();
                        list.add(parseJSON2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
        } catch (Exception e) {
            _log.error("JSON parsing failed");
            return null;
        }
        return map;
    }

}
